package servlet.stu;

import bean.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.UserDaoImpl;
import utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


//学生修改个人信息
@WebServlet("/stu/changeStuInfo")
public class ChangeStuInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String stuName = request.getParameter("stuName");
        String password= null;
        if(request.getParameter("password")!= null) {

            password = request.getParameter("password");
        }
        String user_token = request.getHeader("user_token_header");
        Integer stuId = JwtUtils.getStuIdFromToken(user_token,"stuId");
        Integer age = 0;
        if (request.getParameter("age") != null) {
            age = Integer.parseInt(request.getParameter("age"));

        }
        Integer sex = 0;
        if (request.getParameter("sex") != null) {
            sex = Integer.parseInt(request.getParameter("sex"));

        }
        String phone = null;
        if(request.getParameter("phone")!= null){
            phone = request.getParameter("phone");
        }
        String email =null;
        if(request.getParameter("email") != null) {
            email = request.getParameter("email");
        }
        String college = null;
        if(request.getParameter("college")!= null) {
            college = request.getParameter("college");
        }
        String profession = null;
        if(request.getParameter("profession")!= null) {
            profession = request.getParameter("profession");
        }
        Integer electric = null;
        if(request.getParameter("electric")!= null) {
            electric = Integer.valueOf(request.getParameter("electric"));
        }
        Integer data= null;
        try {
            data = UserDaoImpl.changeStuInfo(stuName, profession, stuId, age, sex, phone, email, college,password,electric);
        } catch (SQLException e) {
            System.out.println(e);
        }
        Result result = new Result();
        if(data!=null){
            result.success(data);
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);


        }else{
            result.fail();
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);


        }

    }
}
